<template>
  <div class="shopinfor">
    <div class="shopinfor_title">店铺信息设置</div>
    <div class="shopinfor_main">
        <el-form
            ref="ruleFormRef"
            label-position="right"
            label-width="auto"
            :model="form"
            :rules="rules"
            style="max-width: 600px"
        >
            <el-form-item label="店铺名称" prop="name">
            <el-input v-model="form.name" />
            </el-form-item>
            <el-form-item label="店铺地址"  prop="address">
            <el-input v-model="form.address" />
            </el-form-item>
            <el-form-item label="店铺Logo" prop="logo">
                 <el-upload 
                    v-model:file-list="fileList"
                    action="#"  
                    ref="uploadRef" 
                    list-type="picture-card" 
                    :auto-upload="false" 
                    :on-preview="handlePictureCardPreview"
                    :on-remove="handleRemove"
                    :on-change="beforeuploadShopLogo">
                    <el-icon><Plus /></el-icon>
                </el-upload>

                <el-dialog v-model="dialogVisible">
                    <img w-full :src="dialogImageUrl" alt="Preview Image" />
                </el-dialog>
            </el-form-item>
        </el-form>
        <div class="submit">
            <button class="submit_btn" @click="submitForm(ruleFormRef)">提交</button>
        </div>

    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'
import { setShopInfor, uploadShopLogo, shopInforList,updateShopInfor } from '@/api/shop/shopinfor'
import { useRoute, useRouter } from 'vue-router'
const route = useRoute()
const router = useRouter()
const { proxy } = getCurrentInstance();
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)
const ruleFormRef = ref()
const uploadRef = ref()
const fileList = ref([])
// 是否修改logo 
const isUploadLogo = ref(false)
const form = ref({
  name: '',
  address:'',
  logo:[]
})  
// 验证上传文件
const validatorFile = (rule, value, callback) => {
  if (fileList.value.length == 0) {
    callback(new Error('请上传店铺logo'))
  } else {
    callback()
  }
}
// 表单检验
const rules = reactive({
  name: [
    { required: true, message: '请输入店铺名称', trigger: 'blur' },
  ],
  address: [
    { required: true, message: '请输入店铺地址', trigger: 'blur' },
  ],
  logo: [
    { required: true, validator: validatorFile },
  ],

})




onMounted(() => {
  getShopInforList()
})

// 获取店铺信息
const getShopInforList = async () => {
  const { name } = route.query
  if(name === 'edit') {
    const res = await shopInforList()
    const { data,code } = res
    if(code === 200) {
      const { name, logo, address, _id} = data[0]
      form.value.name = name
      form.value.address = address
      fileList.value = logo
      form.value['id'] = _id
    }else {
        proxy.$modal.msgError("获取店铺信息失败");
    }
  }
    
}

const handleRemove = (file,list) => {
    isUploadLogo.value = true
    fileList.value = list

}

const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url
  dialogVisible.value = true
}

// 上传之前显示logo
const beforeuploadShopLogo = (file,list) => {
    fileList.value = list
    ruleFormRef.value.validateField('logo')
}
const submitForm = async (formEl) => {
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log(fileList.value,'fileList');
      const { name } =  route.query
      const { url} = fileList.value[0]
      // 先去请求上传接口拿到图片地址
      if(name === 'edit' && !isUploadLogo.value) {
        submitShopInfor(url)
      }else {
        // 上传logo
        uploadLogo()
      }
        
        
    } else {
      console.log('error submit!', fields)
    }
  })
}

// 上传logo
const uploadLogo = async () => {
    const formData = new FormData()
    formData.append('file', fileList.value[0].raw)
    const res = await uploadShopLogo(formData)
    const { data } = res
    if(data) {
        submitShopInfor(data)
    }else {
        proxy.$modal.msgError("上传店铺logo失败");
    }
}

// 提交店铺信息
const submitShopInfor = async (url,id) => {
    const { name, uid } = fileList.value[0]
    // 修改传输的数据格式
    form.value.logo.push({
        status:'success',
        name,
        uid,
        url
    })
    if( route.query.name === 'edit') {
      const res = await updateShopInfor(form.value)
      if(res.code === 200) {
        proxy.$modal.msgSuccess("提交店铺信息成功");
        resetForm()
        router.push('/shop/infor')
      }else {
        proxy.$modal.msgError("提交店铺信息失败");
        resetForm()
      }
    }else {
      const res = await setShopInfor(form.value)
      if(res.code === 200) {
        proxy.$modal.msgSuccess("提交店铺信息成功");
        resetForm()
      }else {
        proxy.$modal.msgError("提交店铺信息失败");
        resetForm()
      }
    }
    
}



// 重置
const resetForm = () => {
  form.value = {
    name: '',
    address:'',
    logo:[]
  };
  // 清除已经上出的文件
  uploadRef.value.clearFiles()
  // 重置表单验证
  proxy.resetForm("ruleFormRef");
}
            
</script>

<style lang='scss' scoped>
.shopinfor {
    width: 100%;
    height: 100%;
    padding: 20px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background-color: #edf2f7;
    .shopinfor_title {
        font-size: 28px;
        color:#000;
        font-weight: 800;
        padding-bottom: 20px;
    }
    .shopinfor_main {
        padding: 100px;
        width: 60%;
        height: 80%;
        background-color: #fff;
        box-shadow:
        2.8px 2.8px 2.2px rgba(0, 0, 0, 0.025),
        6.7px 6.7px 5.3px rgba(0, 0, 0, 0.029),
        12.5px 12.5px 10px rgba(0, 0, 0, 0.032),
        22.3px 22.3px 17.9px rgba(0, 0, 0, 0.035),
        41.8px 41.8px 33.4px rgba(0, 0, 0, 0.04),
        100px 100px 80px rgba(0, 0, 0, 0.07);
        .submit {
            display: flex;
            justify-content: center;
            .submit_btn {
                padding: 17px 40px;
                border-radius: 10px;
                border: 0;
                background-color: rgb(255, 56, 86);
                letter-spacing: 1.5px;
                font-size: 15px;
                transition: all 0.3s ease;
                box-shadow: rgb(201, 46, 70) 0px 10px 0px 0px;
                color: hsl(0, 0%, 100%);
                cursor: pointer;
                margin-top: 60px;
            }
            .submit_btn:hover {
                box-shadow: rgb(201, 46, 70) 0px 7px 0px 0px;
            }
            button:active {
                background-color: rgb(255, 56, 86);
                /*50, 168, 80*/
                box-shadow: rgb(201, 46, 70) 0px 0px 0px 0px;
                transform: translateY(5px);
                transition: 200ms;
            }
        }
        
        
    }
}
</style>